/**
 * @author YinHang
 */
;(function () {
	var Controller = {
		TARGET: {},
		STATES: 0,
		UNIQUE_CODE: 1,
		KEYS: {},
		MOUSE_EVENT_STACK: [],
		MOUSE_EVENT_BUFFER: {},
		addKey: function (keyCode) {
			if(!Controller.KEYS)
				Controller.KEYS = {};
			Controller.KEYS[keyCode] = Controller.UNIQUE_CODE;
			Controller.UNIQUE_CODE <<= 1;
		},
		pushMouseEvent: function (event) {
			event.viewX = event.clientX - Controller.TARGET.offsetLeft;
			event.viewY = event.clientY - Controller.TARGET.offsetTop;
			Controller.MOUSE_EVENT_BUFFER[event.type] = event;
		},
		popMouseEvent: function (type) {
			var event = Controller.MOUSE_EVENT_BUFFER[type];
			delete Controller.MOUSE_EVENT_BUFFER[type];
			return event;
		},
		cleanAllMouseEvent: function () {
			Controller.MOUSE_EVENT_BUFFER = [];
		},
		addKeyList: function (list) {
			var listLength = list.length;
			for(var i=0;i<listLength;++i)
				Controller.addKey(list[i]);
		},
		cleanKeys: function () {
			Controller.KEYS = {};
			Controller.UNIQUE_CODE = 1;
			Controller.STATES = 0;
		},
		removeTarget: function () {
			if(Controller.TARGET)
			{
				delete Controller.TARGET.onmouseup;
				delete Controller.TARGET.onmousedown;
				delete document.onkeyup;
				delete document.onkeydown;
			}
		},
		setTarget: function (target) {
			Controller.removeTarget();
			Controller.TARGET = target;
			Controller.TARGET.onmouseup = function (e) {
				if(e.target == Controller.TARGET)
				{
					Controller.pushMouseEvent(e);
				}
			};
			Controller.TARGET.onmousedown = function (e) {
				if(e.target == Controller.TARGET)
				{
					Controller.pushMouseEvent(e);
				}
			};
			Controller.TARGET.ondbclick = function (e) {
				if(e.target == Controller.TARGET)
				{
					Controller.pushMouseEvent(e);
				}
			};
			Controller.TARGET.onclick = function (e) {
				if(e.target == Controller.TARGET)
				{
					Controller.pushMouseEvent(e);
				}
			};
			Controller.TARGET.onmousemove = function (e) {
				if(e.target == Controller.TARGET)
				{
					Controller.pushMouseEvent(e);
				}
			};
			document.onkeyup = function (e) {
				if(Controller.KEYS[e.keyCode])
					Controller.STATES ^= Controller.KEYS[e.keyCode];
			};
			document.onkeydown = function (e) {
				if(Controller.KEYS[e.keyCode])
					Controller.STATES |= Controller.KEYS[e.keyCode];
			};
		},
		getKeyStates: function () {
			return Controller.STATES;
		},
		getState: function (code) {
			if(Controller.KEYS[code])
				return Controller.getKeyStates() & Controller.KEYS[code];
		}
	};
	
	GameFramework.register(Controller);
})();
